<!-- 工作台-添加个性标签 -->
<template>
  <a-modal
    width="30%"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    :mask-closable="false"
    draggable
    title-align="center"
    unmount-on-close
  >
    <template #title> {{ data?.id ? '编辑' : '新增' }}个性标签 </template>
    <div>
      <a-form :model="formData" :rules="rules" ref="refForm" auto-label-width>
        <a-form-item label="标签名称" field="name" show-colon>
          <a-input
            v-model="formData.name"
            show-word-limit
            allow-clear
            placeholder="请输入"
          ></a-input>
          <template #extra
            >想同时新增多个标签请以逗号分割,例如（标签1,标签2）</template
          >
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { validateRules } from '@/utils/common';
import {
  CheckumanLabel,
  GetHumanSubLabelRepeat
} from '@/apis/management/human/baseSetting/humanSetting';
import { cloneDeep } from 'lodash';
const props = withDefaults(
  defineProps<{
    visible: boolean; // 是否显示对话框
    data?: any; // 传进来的数据
  }>(),
  {
    visible: false
  }
);

const emits = defineEmits(['update:visible', 'tagAddEmit']);

// 模板查重函数
const validateName = async (name: string, cb: any) => {
  try {
    // if (name === props.data?.name && props.data?.id) {
    //   //
    // } else {
    //   const data = {
    //     name,
    //     tagTypeId: props.tagType === 2 ? props.data?.tagTypeId : undefined
    //   };
    //   let res;
    //   if (props.tagType === 1) {
    //     res = await CheckumanLabel(data);
    //   } else {
    //     let arrName = name.split(',');
    //     for (let i = 0; i < arrName.length; i++) {
    //       data.name = arrName[i];
    //       res = await GetHumanSubLabelRepeat(data);
    //       if (res?.code === 400) break;
    //     }
    //   }
    //   if (res?.code === 400) {
    //     cb(`名称已存在`);
    //   }
    // }
  } catch (error: unknown) {
    console.log(error);
  }
};

const rules = {
  name: [
    {
      required: true,
      message: '请输入'
    },
    {
      validator: validateName
    }
  ]
};
let formData = ref({
  name: ''
});

watch(
  () => props.visible,
  (newVal: any) => {
    if (newVal) {
      formData.value.name = cloneDeep(props.data);
    }
  }
);

let refForm = ref();
const handleOk = async () => {
  if (await refForm.value.validate()) {
    return;
  }
  emits('tagAddEmit', formData.value);
  emits('update:visible', false);
  formData.value = {
    name: ''
  };
};

const handleCancel = () => {
  emits('update:visible', false);
  formData.value = {
    name: ''
  };
};
</script>

<style scoped lang="less">
.icon {
  cursor: pointer;
  font-size: 20px;
}
</style>
